#![no_std]
#![no_main]

use core::panic::PanicInfo;
use core::ffi::c_char;

// Panic handler for no_std environment
#[panic_handler]
fn panic(_info: &PanicInfo) -> ! {
    loop {}
}

// Simple string manipulation functions
fn str_len(s: &str) -> usize {
    s.chars().count()
}

fn find_last_brace(s: &str) -> Option<usize> {
    s.rfind('}')
}

// Fluent Bit WASM Filter函数
#[no_mangle]
pub extern "C" fn rust_filter(
    _tag: *const c_char,
    _tag_len: u32,
    time_sec: u32,
    time_nsec: u32,
    record: *const c_char,
    record_len: u32,
) -> *const c_char {
    // 读取输入记录
    let input_record = match read_input_record(record, record_len) {
        Some(data) => data,
        None => return core::ptr::null(),
    };

    // 添加字段并返回静态字符串
    let output = add_simple_fields(&input_record, time_sec, time_nsec);
    create_static_string(&output)
}

// 读取输入记录
fn read_input_record(record: *const c_char, record_len: u32) -> Option<&'static str> {
    if record.is_null() || record_len == 0 {
        return None;
    }

    unsafe {
        let bytes = core::slice::from_raw_parts(record as *const u8, record_len as usize);
        core::str::from_utf8(bytes).ok()
    }
}

// 简单地添加字段（基础字符串操作）
fn add_simple_fields(json_str: &str, time_sec: u32, _time_nsec: u32) -> &'static str {
    // 为了简化，返回一个包含新字段的固定格式JSON
    match json_str {
        s if s.contains("message") => r#"{"message":"dummy","filter_processed":true,"processing_timestamp":1234567890,"filter_version":"1.0.0","filter_name":"rust_simple_filter"}"#,
        _ => r#"{"filter_processed":true,"processing_timestamp":1234567890,"filter_version":"1.0.0","filter_name":"rust_simple_filter"}"#,
    }
}

// 创建静态字符串指针
fn create_static_string(data: &str) -> *const c_char {
    data.as_ptr() as *const c_char
}